package pers.xuyong.strive.datastruct.order.sample;

import pers.xuyong.strive.datastruct.order.AbstractOrder;
import pers.xuyong.strive.datastruct.order.Order;

/**
 * 插入排序
 *
 * @author billymac
 * @version 1.0
 * @date 17/5/23  下午4:37
 * @since JDK1.8
 */
public class InsertOrder<E extends Number> extends AbstractOrder<E>
        implements Order<E> {


    @Override
    public void sort(E[] ts, int method) {
        valid(ts);
        for (int i = 1; i < ts.length; i++) {
            E tmp = ts[i];
            int index = 0;
            for (int j = i - 1; j >= 0; j--) {
                if (method > 0 && ts[j].doubleValue() < tmp.doubleValue() ||
                        method < 0 && ts[j].doubleValue() > tmp.doubleValue())
                    ts[j + 1] = ts[j];
                else  {
                    index = j + 1;
                    break;
                }
            }
            ts[index] = tmp;
        }
    }
}
